<template>
  <div>
    <vab-card>
      <template #header>
        <span class="leve_title">信用档案查询</span>
      </template>
      <template #default>
        <el-form
          :ref="(el: any) => (searchFormRef = el)"
          :model="searchForm"
          label-width="130px"
          class="form_search composite_form"
        >
          <el-row :gutter="24">
            <el-col
              v-for="(item, i) in CustomSearch"
              :key="i"
              :xs="24"
              :sm="12"
              :md="12"
              :lg="8"
              :xl="8"
            >
              <!-- 默认项 -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  :options="selectOptions(item.prop)"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>

              <el-form-item
                v-if="item.type == 'lazySelect'"
                :label="item.label"
                :prop="item.prop"
              >
                <CreditLazySelect
                  :type="item.apiType"
                  :data-type="item.dataType"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabInputForm
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'time'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabTimeForm
                  v-model="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
            </el-col>
            <!-- 按钮 -->
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div class="flex_just_end">
                <el-button size="small" type="primary" @click="handleSearch()">
                  查询
                </el-button>
                <el-button size="small" @click="resetForm(searchFormRef)">
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </vab-card>
    <!-- 主 -->
    <vab-card shadow="always">
      <template #header>
        <div class="flex_sb">
          <span class="leve2_title">信用档案明细</span>
          <div class="flex_just_end">
            <el-button
              size="small"
              class="button_update"
              @click="handleClick('toCustomDetail')"
            >
              信用明细查询
            </el-button>
            <el-button
              size="small"
              class="button_update"
              @click="handleClick('alter')"
            >
              额度变更
            </el-button>
            <el-button
              size="small"
              class="button_update"
              @click="handleClick('apply')"
            >
              申请临时额度
            </el-button>
            <!-- <el-button
              size="small"
              class="button_update"
              type="primary"
              @click="handleClick('create')"
            >
              新建
            </el-button> -->
          </div>
        </div>
      </template>
      <el-table
        border
        height="460"
        style="width: 100%"
        :data="data.dataSource"
        v-loading="data.loading"
      >
        <el-table-column align="center" label="序号" width="60" fixed="left">
          <template #default="scope">
            <label
              class="el-checkbox"
              :class="{ 'is-checked': radioKey == scope.row.id }"
              @click="handleCurrentChange(scope.row)"
            >
              <span
                class="el-checkbox__input"
                :class="{ 'is-checked': radioKey == scope.row.id }"
              >
                <span class="el-checkbox__inner"></span>
              </span>

              <span style="margin-left: 4px;">{{ (data.pageNum - 1) * data.pageSize + (scope.$index + 1) }}</span>
            </label>
          </template>
        </el-table-column>
        <el-table-column align="center" label="信用对象" width="220" fixed="left">
          <template #default="{ row }">
            <span class="ellipsis">{{ row.customer_name || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, i) in data.cloums"
          :key="i"
          :width="item.width"
          :prop="item.prop"
          :label="item.label"
          :align="item.type == 'money' || item.type == 'number' ? 'right' : 'center'
            "
        >
          <template #default="scope">
            <!-- 自定义 -->
            <div v-if="item.type == 'custom'">
              <span
                v-if="item.prop == 'bill_no'"
                class="ellipsis link"
                @click="handleClick('toDetail', scope.row)"
              >
                {{ scope.row[item.prop] || '--' }}
              </span>
              <span
                v-if="item.prop == 'temp_credit_amount'"
                class="ellipsis link"
                @click="temporaryLimitRef.open(scope.row)"
              >
                {{ MoneyFormat(scope.row['temp_credit_amount'], 2) }}
              </span>
              <span v-if="item.prop == 'status'">
                <el-tag
                  class="ml-2"
                  :type="_creditStatusColor(scope.row.status, 'type')"
                >
                  {{ _creditStatusColor(scope.row.status) || '--' }}
                </el-tag>
              </span>
              <span class="ellipsis" v-if="item.prop == 'expiry_date'">
                {{ _priceEncryption(
                  scope.row[item.prop],
                  true,
                  item.prop,
                  scope.row
                ) }}
              </span>

              <!-- 加密 -->
              <span
                v-if="item.iseye"
                class="flex_just_center"
                @click="() => {
                  scope.row[`${item.prop}_disable`] =
                    !scope.row[`${item.prop}_disable`]
                }
                  "
              >
                {{
                  _priceEncryption(
                    scope.row[item.prop],
                    scope.row[`${item.prop}_disable`],
                    item.prop,
                    scope.row
                  )
                }}
                <vab-icon
                  class="eye_icon"
                  icon="eye-line"
                  v-if="scope.row[`${item.prop}_disable`]"
                />
                <vab-icon  class="eye_icon" icon="eye-close-line" v-else />
              </span>
            </div>
            <!-- 正常 -->
            <div v-else class="ellipsis">
              {{ _FieldFormat(scope.row[item.prop], item.type) }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button v-if="isShowToHandle(scope.row.status)" size="small" type="primary" @click="handleOperate('toHandle', scope.row)">去处理</el-button>
            <el-button v-if="isShowToDetail(scope.row.status)"  size="small" type="primary"  @click="handleOperate('toDetail', scope.row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex_just_end">
        <el-pagination
          background
          small="small"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, prev, pager, next,sizes, jumper"
          :page-sizes="[20, 50, 100, 200]"
          :pager-count="10"
          :total="data.count"
          @current-change="handlePageNum"
          @size-change="handlePageSize"
        />
      </div>
    </vab-card>
    <!-- 客户档案-信用编号 -->
    <CustomDetailDialog :ref="(el: any) => (customDetailDialogRef = el)" />

    <!-- 临时信用额度申请 -->
    <TemporaryApplyDialog
      :ref="(el: any) => (temporaryApplyDialogRef = el)"
      @refresh="refresh()"
    />
    <!-- 额度变更 -->
    <CreditLimitChangeDialog
      :ref="(el: any) => (creditLimitChangeDialogRef = el)"
      @refresh="refresh()"
    />
    <!-- 临时额度列表 -->
    <TemporaryLimitDialog
      ref="temporaryLimitRef"
      @refresh="refresh()"
    />
  </div>
</template>
<!-- 草稿箱 -->
<script lang="ts" setup>
defineOptions({
  name: 'CreditCustom',
})
/**
 * @import
 */
import {
  CustomSearch,
  CustomCloums,
  creditStatusColor,
  ReturnSelectOptions,
} from './component/tools'
import {
  DateFormat,
  FieldFormat,
  MoneyFormat,
  NumberFormat,
} from '~/src/utils/utils'
import { ElMessage, FormInstance } from 'element-plus'
import { crediList, crediSearch } from '~/src/api/dms/credit'
import CreditLazySelect from './component/CreditLazySelect.vue'

import { organization_list } from '~/src/api/dms/organization'
import { options_list } from '~/src/api/dms/options'

import CustomDetailDialog from './component/CustomDetailDialog.vue'
import TemporaryApplyDialog from './component/TemporaryApplyDialog.vue'
import TemporaryLimitDialog from './component/TemporaryLimitDialog.vue'
import CreditLimitChangeDialog from './component/CreditLimitChangeDialog.vue'

/**
 * @var
 */
const proxy: any = getCurrentInstance()?.proxy
const router = useRouter()
const searchFormRef = ref<any>(null)
const searchForm = reactive<any>({})
const data = reactive<any>({
  dataSource: [],
  cloums: [],
  pageNum: 1,
  pageSize: 20,
  count: 0,
  search: {},
})
data.dataSource = []
data.cloums = CustomCloums

let isCheck = ref(false)
const currentRow = ref<any>(null) //选中块
const radioKey = ref<any>(-1) //唯一值

const temporaryLimitRef = ref()
const customDetailDialogRef = ref()
const temporaryApplyDialogRef = ref()
const creditLimitChangeDialogRef = ref()

/**
 * @method
 */
const handleSearch = async (value = '') => {
  isCheck.value = true
  await _GetProductList()
  proxy.$Message('查询成功', 'success')
}
// 重置
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  isCheck.value = false

  data.pageNum = 1
  data.pageSize = 20
  await formEl.resetFields()
  await _GetProductList()
  proxy.$Message('重置成功', 'success')
}
// 回车
const onkeydown = (value: any) => {
  isCheck.value = true
  _GetProductList()
}
// 单选
const handleCurrentChange = (row: any) => {
  if (row.id == radioKey.value) {
    radioKey.value = -1
    currentRow.value = null
    return
  }
  radioKey.value = row.id
  currentRow.value = row
}
// 页码
const handlePageNum = (value: any) => {
  data.pageNum = value
  _GetProductList()
}
// 页数
const handlePageSize = (value: any) => {
  data.pageSize = value
  _GetProductList()
}

// 加密
const _priceEncryption = (
  value: string,
  show: boolean,
  prop = '',
  row: any
) => {
  // 天数
  if (prop == 'over_day') return show ? NumberFormat(value) : '***'
  // 有效期
  if (prop == 'expiry_date')
    return row.temp_effective_date && row.temp_expiry_date ? `${row.temp_effective_date}/${row.temp_expiry_date}` : '--'

  // 额度有关
  return show ? MoneyFormat(value, 2) : '***'
}
// 点击事件
const handleClick = (value: any, row = {}) => {
  const _row: any = row

  if (value == 'create') {
    router.push({
      path: '/credit/create',
      query: {
        from: 'create'
      }
    })
    return
  }
  if (value == 'toDetail') {
    customDetailDialogRef.value.open(_row.id)
    return
  }

  if (!currentRow.value) {
    proxy.$Message('请选择需要操作的客户信用明细！', 'warning')
    return
  }

  const { id, status } = currentRow.value

  if (value == 'toCustomDetail') {
    router.push('/credit/customDetail?id=' + id)
    return
  }

  if (status == 4) {
    proxy.$Message(`额度变更中，不能进行${value == 'alter' ? '额度变更' : '申请临时额度'}操作！`, 'warning')
    return
  }
  if (status == 11) {
    proxy.$Message(`临时额度待审核，不能进行${value == 'alter' ? '额度变更' : '申请临时额度'}操作！`, 'warning')
    return
  }

  if (value == 'alter') {
    creditLimitChangeDialogRef.value.open(id)
    return
  }

  if (value == 'apply') {
    temporaryApplyDialogRef.value.open(id)
    return
  }
}
// 操作事件
const handleOperate = (type: string, { status, id }: any) => {
  if (type == 'toHandle') {
    if (status == 6) creditLimitChangeDialogRef.value.open(id)
    if (status == 13) temporaryApplyDialogRef.value.open(id)
  }
  if (type == 'toDetail') {
    customDetailDialogRef.value.open(id)
  }
}

//刷新
const refresh = () => {
  radioKey.value = -1
  currentRow.value = null
  _GetProductList()
}

// 字段级格式化
const _FieldFormat = (value: string, type = '') => {
  if (type == 'time') return DateFormat(value, 'YYYY-MM-DD')
  return FieldFormat(value, type)
}
// 信用状态格式化
const _creditStatusColor = (value: string | number, type = 'label') => {
  const obj = creditStatusColor(value)
  return type == 'label' ? obj.label : obj.type
}
// 筛选项
const _GetProductSearch = async () => {
  try {
    const res = await crediSearch()
    const orgRes = await organization_list({})
    const currencyRes = await options_list({ module: 'currency' })
    data.search = await res.data
    data.search.org_list = await orgRes.data
    data.search.currency = currencyRes.data
  } catch (error) { }
}
// 筛选项返回值
const selectOptions = (value: string) => {
  if (!data.search) return
  if (!value) return
  return ReturnSelectOptions(data.search, value)
}
// 获取数据
const _GetProductList = async () => {
  data.loading = true

  let _searchForm = { ...searchForm }

  if (!isCheck.value) _searchForm = {}

  const query = {
    page: data.pageNum,
    limit: data.pageSize,
    filter: {
      org_id: _searchForm.org_id || '', // 授信组织
      customer_number: _searchForm.customer_number || '', // 客户编码
      customer_name: _searchForm.customer_name || '', // 信用对象
      object_type: _searchForm.object_type || '', // 对象类型
      bill_no: _searchForm.bill_no || '', // 信用编号
      status: _searchForm.status?.toString() ? _searchForm.status : '', // 信用状态
      create_user_id: _searchForm.create_user_id || '', // 创建人
    },
  }

  try {
    const res = await crediList({ ...query })
    data.dataSource = res.data.list.map((item: any) => {
      return {
        ...item,
        credit_amount_disable: false,
        temp_credit_amount_disable: false,
        // expiry_date_disable: false,
        temp_use_credit_amount_disable: false,
        residue_credit_amount_disable: false,
        // over_day_disable: false,
      }
    })
    data.count = res.data.count
    data.loading = false
  } catch (error) { }
}

/**
 * @实例
 */
// 查看详情 2 5 11 12
// 额度变更弹窗 6
// 临时信用额度申请弹窗 13
const isShowToHandle = (status: string | number) => {
  const _status = `${status}`
  if (_status == '6' || _status == '13') return true
  return false
}
const isShowToDetail = (status: string | number) => {
  const _status = `${status}`
  if (_status == '2' || _status == '4' || _status == '5' || _status == '11' || _status == '12') return true
  return false
}

onActivated(async () => {
  currentRow.value = null
  radioKey.value = -1
  await _GetProductList()
  _GetProductSearch()
})
</script>

<style lang="scss" scoped>
@import '../../components/public.scss';
</style>
